package com.bzkj.basicinfo.service.impl.ncc;

import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.bzkj.basicinfo.domain.ncc.NccMaterialAuxiliaryAttributes;
import com.bzkj.basicinfo.mapper.NccMaterialAuxiliaryAttributesMapper;
import com.bzkj.basicinfo.service.ncc.NccMaterialAuxiliaryAttributesService;
import com.bzkj.basicinfo.utils.DataBatchProcessorUtil;
import com.bzkj.basicinfo.utils.HttpClientUtils;
import com.bzkj.common.core.domain.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;

/**
 * @projectName: prt-wms
 * @package: com.bzkj.basicinfo.service.impl.ncc
 * @className: NccMaterialAuxiliaryAttributesServiceImpl
 * @description: NCC医药行业基础信息服务层
 * @author: C1309
 * @createDate: 2025年02月28日
 * @version: v1.0
 */
@Service("nccMaterialAuxiliaryAttributesServiceImpl")
public class NccMaterialAuxiliaryAttributesServiceImpl implements NccMaterialAuxiliaryAttributesService {

    @Resource
    private HttpClientUtils hcu;

    @Resource
    private NccMaterialAuxiliaryAttributesMapper nccMaterialAuxiliaryAttributesMapper;

    @Value("${pk_org.code}")
    private Integer pkOrgCode;
    /**
     * 定时同步医药行业基础信息
     *
     * @return
     */
    @Override
    public R jobMethodExecute(Boolean flag) {
        HashMap<String, String> searchDate = DataBatchProcessorUtil.getSearchDate(flag);

        // 查询当前数据
        HttpResponse response = hcu.methodExecute(searchDate.get("startTimeStr"), searchDate.get("endTimeStr"), 17, pkOrgCode);
        // 收集rep系统数据
        String responseBody = response.body();
        JSONObject entries = JSONObject.parseObject(responseBody);
        JSONArray dataArray = entries.getJSONArray("data");
        List<NccMaterialAuxiliaryAttributes> nccMaterialAuxiliaryAttributes = dataArray.toList(NccMaterialAuxiliaryAttributes.class);
        if (!nccMaterialAuxiliaryAttributes.isEmpty())
            extracted(nccMaterialAuxiliaryAttributes);

        return R.ok("同步成功");
    }

    /**
     * 批量更新或者插入
     *
     * @Date 2024/12/11 14:17:12
     * @Param list
     */
    @Transactional(rollbackFor = Exception.class)
    public void extracted(List<NccMaterialAuxiliaryAttributes> list) {
        for (NccMaterialAuxiliaryAttributes nccMaterialAuxiliaryAttributes : list) {
            nccMaterialAuxiliaryAttributesMapper.insertOrUpdate(nccMaterialAuxiliaryAttributes);
        }
    }
}
